package com.movies.service.controller.user;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.movies.service.common.Constants;
import com.movies.service.common.Result;
import com.movies.service.entity.Comment;
import com.movies.service.entity.Movies;
import com.movies.service.entity.User;
import com.movies.service.service.CommentService;
import com.movies.service.service.MoviesService;
import com.movies.service.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;


@RestController
@RequestMapping("/user/comment")
public class UserCommentController {

    @Autowired
    private CommentService commentService;
    @Autowired
    private UserService userService;
    @Autowired
    private MoviesService moviesService;

//    分页查询电影的评论（按电影ID筛选，支持最小评分过滤）
    @GetMapping("/page")
    public Result page(@RequestParam(defaultValue = "1") Integer pageNo,
                       @RequestParam(defaultValue = "10") Integer pageSize,
                       @RequestParam Long mid,
                       @RequestParam(required = false) Double minScore) {
        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Comment::getMid, mid).ge(minScore != null, Comment::getScore, minScore);
        Page<Comment> page = commentService.page(new Page<>(pageNo, pageSize), wrapper);
        return Result.success(page);
    }

//    分页查询我的评论
    @GetMapping("/my/page")
    @SaCheckLogin
    public Result myPage(@RequestParam(defaultValue = "1") Integer pageNo,
                         @RequestParam(defaultValue = "10") Integer pageSize) {
        Long uid = StpUtil.getLoginIdAsLong();
        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Comment::getUid, uid);
        Page<Comment> page = commentService.page(new Page<>(pageNo, pageSize), wrapper);
        return Result.success(page);
    }

//    发布评论
    @PostMapping
    @SaCheckLogin
    public Result create(@RequestBody CreateCommentReq req) {
        if (req.getMid() == null) {
            return Result.error(Constants.CODE_600, "缺少电影ID");
        }
        if (req.getScore() == null || req.getContent() == null) {
            return Result.error(Constants.CODE_600, "评分与内容不能为空");
        }
        Long uid = StpUtil.getLoginIdAsLong();
        User user = (User) StpUtil.getSession().get("user");
        if (user == null) { user = userService.getById(uid); }
        Movies m = moviesService.getById(req.getMid());
        Comment c = new Comment();
        c.setUid(uid);
        c.setUname(user != null ? user.getUname() : null);
        c.setMid(req.getMid());
        c.setMname(m != null ? m.getMname() : req.getMname());
        c.setTid(req.getTid());
        c.setScore(BigDecimal.valueOf(req.getScore()));
        c.setContent(req.getContent()); // 富文本
        boolean ok = commentService.save(c);
        return ok ? Result.success("发布成功", c) : Result.error(Constants.CODE_600, "发布失败");
    }

//    更新我的评论
    @PutMapping
    @SaCheckLogin
    public Result update(@RequestBody UpdateCommentReq req) {
        Long uid = StpUtil.getLoginIdAsLong();
        Comment c = commentService.getById(req.getId());
        if (c == null || !uid.equals(c.getUid())) {
            return Result.error(Constants.CODE_401, "无权操作该评论");
        }
        if (req.getScore() != null) {
            c.setScore(BigDecimal.valueOf(req.getScore()));
        }
        c.setContent(req.getContent());
        boolean ok = commentService.updateById(c);
        return ok ? Result.success("更新成功") : Result.error(Constants.CODE_600, "更新失败");
    }

//    删除我的评论
    @DeleteMapping("/{id}")
    @SaCheckLogin
    public Result delete(@PathVariable Long id) {
        Long uid = StpUtil.getLoginIdAsLong();
        Comment c = commentService.getById(id);
        if (c == null || !uid.equals(c.getUid())) {
            return Result.error(Constants.CODE_401, "无权操作该评论");
        }
        boolean ok = commentService.removeById(id);
        return ok ? Result.success("删除成功") : Result.error(Constants.CODE_600, "删除失败");
    }

    /** 发布评论请求体 */
    public static class CreateCommentReq {
        private Long mid;
        private Long tid;
        private String mname;
        private Double score;
        private String content; // 富文本
        public Long getMid() { return mid; }
        public void setMid(Long mid) { this.mid = mid; }
        public Long getTid() { return tid; }
        public void setTid(Long tid) { this.tid = tid; }
        public String getMname() { return mname; }
        public void setMname(String mname) { this.mname = mname; }
        public Double getScore() { return score; }
        public void setScore(Double score) { this.score = score; }
        public String getContent() { return content; }
        public void setContent(String content) { this.content = content; }
    }

    /** 更新评论请求体 */
    public static class UpdateCommentReq {
        private Long id;
        private Double score;
        private String content; // 富文本
        public Long getId() { return id; }
        public void setId(Long id) { this.id = id; }
        public Double getScore() { return score; }
        public void setScore(Double score) { this.score = score; }
        public String getContent() { return content; }
        public void setContent(String content) { this.content = content; }
    }
}